//
//  YiDaNet.swift
//  YiDa
//
//  Created by zhoufei on 16/6/27.
//  Copyright © 2016年 ZhouFei. All rights reserved.
//

import Foundation

class YiDaNet: NSObject {
    class var main:YiDaNet{
        struct Static {
            static let instance:YiDaNet = YiDaNet()
        }
        
        return Static.instance
    }
    
    
    func request(url:String,param:Dictionary<String,AnyObject>?,method:String = "POST",completionHandler:(inner:() throws ->Dictionary<String, AnyObject>) -> ()){
        let url: NSURL = NSURL(string: url)!
        let request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
        var body:String = ""
        var p:NSData!
        do{
            p = try NSJSONSerialization.dataWithJSONObject(param!, options: .PrettyPrinted)
            body = String.init(data: p, encoding: NSUTF8StringEncoding)!
        }catch {
            print(error)
            completionHandler(inner: {return ["error_code":1,"error_msg":"数据转换失败"]})
            return
        }
        
        
        if body.characters.count > 0{
            request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)
        }
        
        request.HTTPMethod = method
        let loadDataSourceQueue = NSOperationQueue();
        NSURLConnection.sendAsynchronousRequest(request, queue: loadDataSourceQueue) { (response, data, error) in
            if (error != nil){
                print(error?.localizedDescription)
            }else{
                print(NSString(data: data!, encoding: NSUTF8StringEncoding))
                do{
                    let json:Dictionary<String, AnyObject> = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! Dictionary<String, AnyObject>
                    completionHandler(inner: {return json})
                }catch let error{
                    print(error)
                    completionHandler(inner: {return ["error_code":1,"error_msg":"数据转换失败"]})
                }
                
            }
        }
    }
    
}
